#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>

#define   MMSIZE   128

int main(int argc, char *argv[])
{
    int len;
    char wr_buf[] = "hello mmap";
	char read_buf[1024];
	char *start;

    if(argc < 2){
        printf("please input  at least 2 args\n");
        printf("%s <dev> [string]\n", argv[0]);
        return -1;
    }

    /*open*/
    int fd;
    fd = open(argv[1], O_RDWR);
    if(fd < 0){
        printf("open failed\n");
        return -2;
    }

	printf("pid = %d\n", getpid());

	/* 将文件映射到进程的虚拟内存空间 */
	start = mmap(NULL, MMSIZE, PROT_READ | PROT_WRITE, 
		 MAP_SHARED, fd, 0);

	printf("mmap address = 0x%x\n", start);

	/* 写数据 */
	strcpy(start, wr_buf);

	/* 读数据 */
//	strcpy(read_buf, start);
	read(fd, read_buf, MMSIZE);

	printf("new data = %s\n", start);
	printf("old data = %s\n", read_buf);

//	printf("read data = %s, match is %s\n", read_buf,
//			strcmp(read_buf, start)==0 ? "OK" : "NO");
		 
	while(1){
		sleep(5);
	}

	munmap(start, MMSIZE);
    
    close(fd);

    return 0;
}

